import Taro, { Component } from '@tarojs/taro'
import { View, Text, Picker } from '@tarojs/components'
import classNames from 'classnames'
import { DNavBar, DAtInpute, DSelectColor } from '@/components'
import { AtForm, AtButton, AtActionSheet, AtIcon, AtCheckbox } from 'taro-ui'
import { connect } from '@tarojs/redux'
import { getadvanceinfo } from '../../actions/counter'
import http from '@/api'
import dayjs from 'dayjs'
import common from '@/common'
import sdk from '@/common/sdk'
import './advanceform.scss'

const itemplace = require('../logisticsform/place.png')


@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  nextStepForm(obj) {
    dispatch(getadvanceinfo(obj))
  }
}))

export default class AdvanceformBox extends Component {
  constructor(props) {
    super(props)
    this.state = {
      amMonitorTypeArr: [],
      listColr: [],
      seletOne: {
        defNoop: () => {
          this.state.seletOne.isOpened = false
          this.setState({
            seletOne: { ...this.state.seletOne },
          })
        }
      }, // 单选对象
      advanceform: {
        amLogisEnd: "",
        amLogisStart: "",
        amLogisStartTitle: "",
        amLogisEndTitle: "",
      },
      // 颜色key值
      colorKey: "",
      selectColor: "",
      colorCount: 2,
      id: '',
      startTime: dayjs().format('YYYY-MM-DD'),
      title: '代购申请',
      type: 1
    }
  }

  componentWillMount() {
    let { id = '', type = '' } = this.$router.params // 6a865a50681d443a962dbb59f0f0de03

    this.getEntInfo()
    this.setState({
      id,
      typeForm: type,
      AvailableQuota: this.$router.params.AvailableQuota
    }, () => {
      if (id) {
        this.getAdvanceinfoForm()
      }
    })
  }

  componentDidShow() {
    this.getCarBrand()
    sdk.setTitleInfo(this.state.title)
    this.getAddress()
  }

  getAddress() {
    let addressInfo = JSON.parse(sessionStorage.getItem('_addreinfo'))
    if (!addressInfo) return

    let { advanceform, type } = this.state

    if (type == 1) {
      advanceform.amLogisStart = addressInfo.desc
      advanceform.amLogisStartTitle = addressInfo.title
    } else if (type == 2) {
      advanceform.amLogisEnd = addressInfo.desc
      advanceform.amLogisEndTitle = addressInfo.title
    }

    this.setState({ advanceform }, () => {
      sessionStorage.removeItem('_addreinfo')
    })
  }

  async getEntInfo() {
    let { entId: id }  = await http.myselfDetail()

    const { entName } = await http.getEntinfo({ id })
    const { advanceform } = this.state
    advanceform.entName = entName

    this.setState({
      advanceform
    })
  }
  getAdvanceinfoForm() {
    let { id } = this.state
    http.getOrderDetail({ id }).then(res => {
      if (!JSON.stringify(res)) {
        return
      }
      let _obj = [
        // 'amSale',
        // 'amSaleContact',
        'vehicleOwnerName',
        'amTailMoneyComp',
        'amSpendPeriod',
        'amSpendDate',
        'amCarType',
        'amMoney',
        'amContractMoney',
        'downPayment',
        'amCarOutColor',
        'amCarInColor',
        'amCarNo',
        'amLogisStart',
        'amLogisEnd',
        'amMonitorType',
        'amMonitorAddr'
      ]
      let { advanceform } = this.state
      _obj.map(item => {
        advanceform[item] = res[item]
      })
      advanceform.amLogisStartTitle = res.amLogisStart
      advanceform.amLogisEndTitle = res.amLogisEnd

      this.setState({
        advanceform
      })
    })
  }

  initSelectOne = ({ title, bind, checkbox }, sList) => {
    return new Promise((res, rej) => {
      this.setState({
        seletOne: {
          ...this.state.seletOne,
          isOpened: true,
          title,
          checkbox,
          sList: sList.filter(item => (item.status = this.state.advanceform[bind] === item.text, true)), // 反显高亮值
          selectListItem: (item) => {

            item.status = !item.status
            if (item.status) {

              this.state.seletOne.value = item

              res.call(this, item)
            }
            if (!checkbox) {
              this.state.seletOne.isOpened = false
            } else {
              this.state.advanceform[bind]
            }

            this.setState({
              seletOne: { ...this.state.seletOne },
            })
          },
        }
      })
    })
  }
  onRightHanldeColor(key) {
    let { waiguanyanse, neigaunyanse } = this.state
    this.setState({
      isOpenedColor: true,
      colorKey: key,
      listColr: common.getSplitColor(key === 'amCarOutColor' ? waiguanyanse : neigaunyanse),
      colorCount: key === 'amCarOutColor' ? 0 : 2,
      selectColor: this.state.advanceform[key]
    });
  }

  onCancelHandle() {
    this.setState({
      isOpenedColor: false
    });
  }

  onSubmitColor(value) {
    let { colorKey } = this.state;
    let color = [];
    value.map(item => {
      color.push(item.color);
    });
    this.bindCarform(colorKey, color.join('/'));
    this.setState({
      isOpenedColor: false
    });
  }
  handleChange(val) {
    this.setState({
      amMonitorTypeArr: val
    })
    this.bindCarform('amMonitorType', val)
  }
  bindCarform = (key, value) => {
    if (key) {
      if (key == 'amMonitorType') {
        // this.state.amMonitorTypeArr[value]
        value = value.join('/')
      }
      let moneyMap = ['amMoney', 'amContractMoney', 'downPayment']

      if (moneyMap.includes(key)) {
        value = value.match(/^\d+(?:\.\d{0,4})?/) ? value.match(/^\d+(?:\.\d{0,4})?/)[0] : ''
      }
      this.setState({
        // amMonitorTypeArr:this.state.amMonitorTypeArr,
        advanceform: Object.assign(this.state.advanceform, { [key]: value })
      })
    }
  }

  selectCarSource = (props) => {
    this.initSelectOne(props, [
      { text: '车辆监管' },
      { text: '证件监管' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }
  selectAddreSource = (props) => {
    this.initSelectOne(props, [
      { text: '广东省广州市天河区利通大厦1号' },
      { text: '广东省广州市员村一横路1号' },
      { text: '展融到店' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  onSelectData = (props) => {
    this.initSelectOne(props, [
      { text: '3' },
      { text: '7' },
      { text: '15' },
      { text: '30' }
    ]).then(selectItem => {
      this.bindCarform(props.bind, selectItem.text)
    })
  }

  onRightHanlde() {
    Taro.navigateTo({
      url: "/pages/choosebrand/choosebrand"
    })
  }
  getCarBrand() {
    let _brandList = sessionStorage.getItem('brandList')
    if (!_brandList) {
      return
    }
    let { carBrandId = '',
      neigaunyanse = '',
      waiguanyanse = '',
      carBrandLogo = '', carModel = '', carSourceType = '', carGuiPrice = '', carModelId = '' } = JSON.parse(_brandList)
    let _obj = {
      carDataBrandId: carBrandId,
      carDataBrandLogo: carBrandLogo,
      carDataModel: carModel,
      carSourceType: carSourceType,
      carGuiPrice: carGuiPrice,
      carDataModelId: carModelId,
      // amCarOutColor:waiguanyanse,
      // amCarInColor:neigaunyanse
    }
    this.bindCarform('amCarType', carModel)
    // let advanceform = Object.assign(this.state.advanceform, _obj)
    this.setState({
      // advanceform,
      waiguanyanse,
      neigaunyanse,

    })
    sessionStorage.removeItem('brandList')
  }

  onChangeTime(e) {
    let { value } = e.detail
    this.bindCarform('amSpendDate', value)
  }

  nextStep() {
    let _obj = [
      // 'amSale',
      // 'amSaleContact',
      'vehicleOwnerName',
      'amTailMoneyComp',
      'amSpendPeriod',
      'amSpendDate',
      'amCarType',
      'amMoney',
      'amContractMoney',
      'downPayment',
      'amCarOutColor',
      // 'amCarInColor',
      // 'amCarNo',
      'amLogisStart',
      'amLogisEnd',
      'amMonitorType',
      // 'amMonitorAddr'
    ]
    const objText = {
      // amSale: '请输入卖家企业名称',
      // amSaleContact: '请输入卖家联系方式',
      vehicleOwnerName: '请输入车主姓名',
      amTailMoneyComp: '请输入尾款进账企业名称',
      amSpendPeriod: '请选择用款天数',
      amSpendDate: '请选择用款日期',
      amCarType: '请选择交易车型',
      amMoney: '请输入代购金额',
      amContractMoney: '请输入合同金额',
      downPayment: '请输入首付款金额',
      amCarOutColor: '请输入车辆外观颜色',
      // amCarInColor: '请输入车辆内饰颜色',
      // amCarNo: '请输入车架号',
      amLogisStart: '请输入物流始发地',
      amLogisEnd: '请输入物流目的地',
      amMonitorType: '请选择监管方式',
      // amMonitorAddr: '请选择监管地址'
    }
    let _status = false, _item = ''
    let { advanceform, typeForm, AvailableQuota } = this.state
    // _obj.map(item => {
    //     if (!advanceform[item]) {
    //         _status = true
    //     }
    // })
    for (let i = 0, j = _obj.length; i < j; i++) {
      if (!advanceform[_obj[i]]) {
        _status = true
        _item = _obj[i]
        break
      }
    }
    if (_status) {
      return Taro.showToast({
        icon: 'none',
        title: objText[_item]
      })
    }
    if (Number(advanceform['amMoney']) > Number(AvailableQuota)) {
      return Taro.showToast({
        icon: 'none',
        title: "代购金额不可超过可用额度"
      })
    }
    let edit
    if (this.$router.params.id) {
      edit = true
    }
    Taro.navigateTo({
      url: `/pages/advanceupload/advanceupload?type=${typeForm}&id=${this.$router.params.id}&edit=${edit}`
    }).then(() => {
      sessionStorage.setItem('advaceform', JSON.stringify(advanceform))
      // this.props.nextStepForm(advanceform)
    })
  }

  onSelectMap(value, address) {
    this.setState({
      type: value
    }, () => {
      Taro.navigateTo({
        url: `/pages/selectmap/selectmap?type=${this.state.type}&address=${address}`
      })
    })
  }

  render() {
    const {
      advanceform,
      seletOne,
      startTime,
      title,
      listColr,
      colorCount,
      selectColor,
      isOpenedColor
    } = this.state
    const _bindCarform = function (value) {
      this.bindCarform(arguments[arguments.length - 1].bind, value)
    }
    this.checkboxOption = [{ value: '车辆监管', label: '车辆监管' },
    { value: '证件监管', label: '证件监管' }]
    return (
      <View className='b_advanceform'>
        <DNavBar title={title}></DNavBar>
        <View className='b_advanceform__box'>
          <View className='b_advanceform__form'>
            <AtForm>
              <View className='b_advanceform__form__item'>
                <Text className='b_advanceform__form_title'>基本信息</Text>
                {/* <DAtInpute require maxLength={14} onChange={_bindCarform.bind(this)} bind='amSale' value={advanceform.amSale} title='上游公司' placeholder='请输入上游公司'></DAtInpute> */}
                <DAtInpute require maxLength={14} onChange={_bindCarform.bind(this)} bind='vehicleOwnerName' value={advanceform.vehicleOwnerName} title='车主姓名' placeholder='请输入车主姓名'></DAtInpute>

                <View className="form-item">
                  <View className="form-item-label">申请人公司</View>
                  <View className="form-item-value">{advanceform.entName}</View>
                </View>

                {/* <DAtInpute require maxLength={14} onChange={_bindCarform.bind(this)} bind='amSaleContact' value={advanceform.amSaleContact} type='phone' title='上游公司联系方式' placeholder='请输入上游公司联系方式'></DAtInpute> */}
                <DAtInpute require maxLength={14} onChange={_bindCarform.bind(this)} bind='amTailMoneyComp' value={advanceform.amTailMoneyComp} title='尾款进账公司名' placeholder='请输入尾款进账企业名称'></DAtInpute>
                <DAtInpute require type='number' maxLength={5} onChange={_bindCarform.bind(this)} bind='amSpendPeriod' value={advanceform.amSpendPeriod} title='用款天数' icon='chevron-right' placeholder='请选择用款天数' onRightHanlde={this.onSelectData}>{advanceform.amSpendPeriod ? '天' : ''}</DAtInpute>
                {/* <DAtInpute onChange={_bindCarform.bind(this)} bind='amSpendDate' value={advanceform.amSpendDate} title='用款日期' icon='chevron-right' placeholder='请选择用款日期'></DAtInpute> */}
                <Picker mode='date' start={startTime} value={'YYYY-MM-DD'} onChange={this.onChangeTime.bind(this)}>
                  <View className='b_advanceform__time'>
                    <View className='b_advanceform__time_text'>用款日期</View>
                    <View className='b_advanceform__time_value'>
                      <View className={classNames('b_advanceform__time_value__item', advanceform.amSpendDate ? 'b_advanceform__time_active' : '')}>{advanceform.amSpendDate || '请选择用款日期'}</View>
                      <AtIcon value='chevron-right' color='#ccc' size='24'></AtIcon>
                    </View>
                  </View>
                </Picker>
                <DAtInpute require onChange={_bindCarform.bind(this)} bind='amCarType' value={advanceform.amCarType} title='选择车型' icon='chevron-right' placeholder='请选择交易车型' onRightHanlde={this.onRightHanlde.bind(this)}></DAtInpute>
                <DAtInpute maxLength={8} require onChange={_bindCarform.bind(this)} bind='amMoney' value={advanceform.amMoney} title='代购金额' placeholder='请输入代购金额 '>
                  <Text className='item_text'>万</Text>
                </DAtInpute>
                <DAtInpute maxLength={8} require onChange={_bindCarform.bind(this)} bind='amContractMoney' value={advanceform.amContractMoney} title='合同金额' placeholder='请输入合同金额 '>
                  <Text className='item_text'>万</Text>
                </DAtInpute>
                <DAtInpute maxLength={8} require onChange={_bindCarform.bind(this)} bind='downPayment' value={advanceform.downPayment} title='首付款金额' placeholder='请输入首付款金额 '>
                  <Text className='item_text'>万</Text>
                </DAtInpute>
              </View>
              <View className='b_advanceform__form__item'>
                <Text className='b_advanceform__form_title'>车辆信息</Text>
                <DAtInpute value={advanceform.amCarOutColor} bind="amCarOutColor" onChange={_bindCarform.bind(this)} title="外观颜色" require={true} icon="chevron-right" placeholder="请选择车辆外观颜色" onRightHanlde={this.onRightHanldeColor.bind(this, 'amCarOutColor')}></DAtInpute>
                <DAtInpute value={advanceform.amCarInColor} bind="amCarInColor" onChange={_bindCarform.bind(this)} title="内饰颜色" icon="chevron-right" placeholder="请选择车辆内饰颜色" onRightHanlde={this.onRightHanldeColor.bind(this, 'amCarInColor')}></DAtInpute>
                <DAtInpute onChange={_bindCarform.bind(this)} bind='amCarNo' value={advanceform.amCarNo} maxLength={15} title='车架号' placeholder='请输入车架号'></DAtInpute>
                {/* <DAtInpute require onChange={_bindCarform.bind(this)}  maxLength={100} value={advanceform.amLogisStart} title='物流始发地' placeholder='请输入物流始发地'></DAtInpute> */}
                <DAtInpute className="_textOv" require  value={advanceform.amLogisStartTitle} title={'物流始发地'}  placeholder='请选择物流始发地' image={itemplace} onRightHanlde={this.onSelectMap.bind(this, 1, advanceform.amLogisStartTitle)}></DAtInpute>
                <DAtInpute className="_textOv" require value={advanceform.amLogisEndTitle} title={'物流目的地'}  placeholder='请选择物流目的地' image={itemplace} onRightHanlde={this.onSelectMap.bind(this, 2, advanceform.amLogisEndTitle)}></DAtInpute>
                {/* <DAtInpute require onChange={_bindCarform.bind(this)} maxLength={100} value={advanceform.amLogisEnd} title='物流目的地' placeholder='请输入物流目的地'></DAtInpute> */}
              </View>
              <View className='b_advanceform__form__item'>
                <Text className='b_advanceform__form_title'>监管信息</Text>
                <DAtInpute require onChange={_bindCarform.bind(this)} bind='amMonitorType' value={advanceform.amMonitorType} title='监管方式' checkbox icon='chevron-right' placeholder='请选择监管方式' onRightHanlde={this.selectCarSource}></DAtInpute>
                {/* <DAtInpute require onChange={_bindCarform.bind(this)} bind='amMonitorAddr' value={advanceform.amMonitorAddr} title='监管地址' icon='chevron-right' placeholder='请选择监管地址' onRightHanlde={this.selectAddreSource}></DAtInpute> */}
              </View>
            </AtForm>
          </View>
          <View className='b_advanceform__footer'>
            <AtButton className='item_btn' onClick={this.nextStep.bind(this)} >下一步</AtButton>
          </View>
        </View>
        <View>
          <AtActionSheet className="at-select-one" isOpened={seletOne.isOpened} onClose={seletOne.onClose || seletOne.defNoop}>
            <View className='at-select-one__title'>
              <View className='at-select-one__title_cancel' onClick={seletOne.cancel || seletOne.defNoop}>{seletOne.cancelText || '取消'}</View>
              <View className='at-select-one__title_item'>{seletOne.title}</View>
              <View className='at-select-one__title_submit' onClick={seletOne.commit || seletOne.defNoop}>{seletOne.commitText || '提交'}</View>
            </View>
            <View className='at-select-one__type'>
              {
                !seletOne.checkbox && seletOne.sList && seletOne.sList.map((item, i) => {
                  return <View onClick={seletOne.selectListItem.bind(this, item)} className={classNames('at-select-one__type_item', item.status ? 'at-select-one__active' : '')} key={i}>{item.text}</View>
                })
              }
              {seletOne.checkbox && seletOne.sList && <AtCheckbox
                options={this.checkboxOption}
                selectedList={this.state.amMonitorTypeArr}
                onChange={this.handleChange.bind(this)}
              />}
            </View>
          </AtActionSheet>
          <DSelectColor list={listColr} count={colorCount} value={selectColor} isOpened={isOpenedColor} onCancelHandle={this.onCancelHandle.bind(this)} onSubmitHandle={this.onSubmitColor.bind(this)}></DSelectColor>

        </View>
      </View>
    )
  }
}
